﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows.Media.TextFormatting;

namespace SDF.TextFormatting
{
    public class SmartTextFragment
    {
        #region Constructor

        public SmartTextFragment(TextRun source)
        {
            Source = source;
        }

        public SmartTextFragment(UIElementContainer container)
        {
            Source = container;
        }

        #endregion

        #region Properties

        public SmartInline Source { get; private set; }

        public virtual int Length
        {
            get
            { 
                if (Source == null)
                    return 0;

                var run = Source as TextRun;
                if (run != null)
                    return run.Text.Length;

                var embeddedObject = Source as UIElementContainer;
                if (embeddedObject != null)
                    return 1;

                throw new NotSupportedException(String.Format("Type {0} is not supported by SmartTextFragment.", Source.GetType()));
            }
        }

        #endregion

        #region GetTextRun Method

        public virtual System.Windows.Media.TextFormatting.TextRun GetTextRun(int offset)
        {
            if (this == SmartTextFragment.LineBreak)
                return new TextEndOfLine(this.Length);

            var run = Source as TextRun;
            if (run != null)
            {
                // Return an instance of TextCharacters using the current font rendering properties.
                var textRunProperties = new SmartTextRunProperties(run);

                return new TextCharacters(
                    run.Text,
                    offset,
                    run.Text.Length - offset,
                    textRunProperties);
            }

            var embeddedObject = Source as UIElementContainer;
            if (embeddedObject != null)
            {
                // Return an instance of SmartTextEmbeddedObject
                return new SmartTextEmbeddedObject(embeddedObject);
            }

            throw new NotSupportedException(String.Format("Type '{0}' is not supported by SmartTextSource.", Source.GetType()));
        }

        #endregion

        #region Constants

        public static readonly SmartTextFragment LineBreak = new SmartTextFragment(new TextRun(Environment.NewLine)); 

        #endregion
    }
}
